package com.sq.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sq.common.exception.NoStockException;
import com.sq.common.to.mq.OrderTo;
import com.sq.common.to.mq.SeckillOrderTo;
import com.sq.common.utils.R;
import com.sq.common.vo.MemberRespVo;
import com.sq.gulimall.order.constant.OrderConstant;
import com.sq.gulimall.order.entity.OrderItemEntity;
import com.sq.gulimall.order.entity.PaymentInfoEntity;
import com.sq.gulimall.order.enume.OrderStatusEnum;
import com.sq.gulimall.order.feign.CartFeignService;
import com.sq.gulimall.order.feign.MemberFeignService;
import com.sq.gulimall.order.feign.ProductFeignService;
import com.sq.gulimall.order.feign.WmsFeignService;
import com.sq.gulimall.order.interceptor.LoginUserInterceptor;
import com.sq.gulimall.order.service.OrderItemService;
import com.sq.gulimall.order.service.PaymentInfoService;
import com.sq.gulimall.order.to.OrderCreateTo;
import com.sq.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sq.common.utils.PageUtils;
import com.sq.common.utils.Query;

import com.sq.gulimall.order.dao.OrderDao;
import com.sq.gulimall.order.entity.OrderEntity;
import com.sq.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页逻辑
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程..." + Thread.currentThread().getId());

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有的收货地址列表
            System.out.println("member线程..." + Thread.currentThread().getId());
            //每一个线程都共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车里面 所有选中的购物项
            System.out.println("cart线程..." + Thread.currentThread().getId());
            //每一个线程都共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
            /**
             * Feign在远程调用之前要构造请求，调用很多的拦截器
             * RequestInterceptor interceptor : requestInterceptors
             */
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream()
                    .map(item -> item.getSkuId()).collect(Collectors.toList());

            //TODO 启动库存服务查询库存
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream()
                        .collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);

        //3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);
        //4.其他数据自动计算

        //TODO 5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(),
                token, 30, TimeUnit.MINUTES); //给服务器一个令牌，存储在Redis中

        confirmVo.setOrderToken(token); //给页面一个令牌
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        return confirmVo;
    }

    /**
     * 提交订单 下单操作
     *
     * @param vo
     * @return
     */
    //本地事务：整个提交订单作为一个事务，在分布式系统下,只能控制自己的回滚，控制不了其他服务的回滚。
    //分布式事务：最大原因，网络问题 + 分布式机器
    //(isolation = Isolation.REPEATABLE_READ) 可重复读 mySql 默认的隔离级别
//    @GlobalTransactional    //seata的全局事务 高并发场景下AT模式不适用
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo); //将页面传来的所有数据，都放到 ThreadLocal 里面
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0); //没有问题就是成功
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 1.验证令牌 【令牌的对比和删除 必须保证原子性】
        //这个脚本返回的都是 0 和 1
        //0 令牌校验失败  1 校验成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();//客户端的防重令牌

        //redis执行脚本   原子验证令牌和删除令牌
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else {
            //令牌验证成功
            // 下单：去创建订单，验证令牌，验价格，锁库存。。。

            //1.创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比 验价成功 两个价格一样

                // TODO 3.保存订单
                saveOrder(order);
                //4.库存锁定，只要有异常，回滚订单数据
                //订单号 订单项信息（skuId，num，skuName）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());

                    return itemVo;
                }).collect(Collectors.toList());

                lockVo.setLocks(locks);
                //TODO 4.调用远程方法锁定库存
                //库存成功了，但是网络原因超时了，还是会造成订单回滚，库存不回魂

                //为了保证高并发，库存服务自己回滚。 可以发消息给库存服务；
                //库存服务也可以本身使用自动解锁模式  使用消息队列
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    response.setOrder(order.getOrder());

                    //TODO 5.远程扣减积分
//                    int i = 10/0; //订单回滚，库存不回滚
                    //TODO 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange",
                            "order.create.order",
                            order.getOrder());
                    return response;
                } else {
                    //库存锁定失败
                    //抛出库存不足异常，让整个提交订单事务回滚，撤销之前所有的操作
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                //验价失败 提交订单的商品价格 与 商品的实时价格 有误差
                response.setCode(2);
                return response;
            }
        }


        //用脚本来实现下面的逻辑
//        String redisToken = (String) redisTemplate.opsForValue()
//                .get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());//redis中服务器的防重令牌
//        if(orderToken != null && orderToken.equals(redisToken)){
//            //令牌验证通过
//        }else{
//            //令牌验证不通过
//        }
    }

    /**
     * 根据订单号获取订单数据
     *
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 待付款订单超时，自动关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //超时，关闭订单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());//订单状态设置为已取消 status = 4
            this.updateById(update);
            //发给MQ一个订单释放的消息，让其解锁库存，避免网络等原因导致库存被锁定
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                //TODO 定期扫描数据库，将失败的消息再发送一遍。
                rabbitTemplate.convertAndSend("order-event-exchange",
                        "order.release.other",
                        orderTo);
            } catch (Exception e) {
                //TODO 将没发送成功的消息进行重试发送

            }
        }
    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);//保留小数点后2位，向上取值

        List<OrderItemEntity> order_sn = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 查询订单项数据
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberRespVo.getId())
                        .orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(
                    new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //2.修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());

        }
        return "success";
    }

    /**
     * 保存秒杀订单信息
     * @param seckillOrder
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply); //应付价格

        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        //TODO 获取当前sku的详细信息进行设置
//        productFeignService.getSpuInfoBySkuId(seckillOrder.getSkuId());

        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        //保存订单
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        //保存订单项数据
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1.生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单的 基本信息项
        OrderEntity orderEntity = buildOrder(orderSn);

        //2.构建订单项的数据
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3.计算价格,积分 等相关的信息
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    /**
     * 计算价格相关的信息
     *
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //订单的总额
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");

        //订单的总额  叠加每一项订单项的总额信息
        for (OrderItemEntity itemEntity : itemEntities) {

            integration = integration.add(itemEntity.getIntegrationAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            coupon = coupon.add(itemEntity.getCouponAmount());
            total = total.add(itemEntity.getRealAmount());

            growth = growth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));
            gift = gift.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
        }

        // 1.订单价格相关
        orderEntity.setTotalAmount(total);
        //订单应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        //设置订单删除状态
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 构建订单基本信息
     *
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId()); //会员id

        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        //获取收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });

        //设置运费金额
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人的城市
        entity.setReceiverCity(fareResp.getAddress().getCity());
        //设置收货地址
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        //设置收货人名字
        entity.setReceiverName(fareResp.getAddress().getName());
        //设置收货人电话
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        //设置收货人邮编
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        //设置收货人省份
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        //设置收货人市区
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }

    /**
     * 构建所有的订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定 每个购物项的价格 最后的成交价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                //把每一个  购物项  映射成对应的 订单项
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());

            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项数据
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息：订单号
        //2.商品的SPU信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //3.商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());

        //4.优惠信息 【不做】
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(
                new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(
                new BigDecimal(cartItem.getCount().toString())).intValue());
        //6.订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额  sku单价乘数量  总额 减去 各种优惠金额
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
        BigDecimal subtract = origin.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }
}